package com.wtwd.device.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtwd.device.constant.SeparatorConstant;
import com.wtwd.device.dao.HealthTypeContentMapper;
import com.wtwd.device.model.entity.ExcelImporthealthTypeLanguage;
import com.wtwd.device.model.entity.HealthTypeContent;
import com.wtwd.device.model.vo.HealthTypeContentVo;
import com.wtwd.device.service.FileService;
import com.wtwd.device.service.HealthTypeContentService;
import com.wtwd.device.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2023-08-16
 */
@Service
public class HealthTypeContentServiceImpl extends ServiceImpl<HealthTypeContentMapper, HealthTypeContent> implements HealthTypeContentService {

    @Value("${file.path}")
    private String filePath;

    @Value("${healthContent.excel}")
    private String healthContentPath;

    @Value("${file.http}")
    private String fileHttp;

    @Resource
    private HealthTypeContentMapper healthTypeContentMapper;

    @Resource
    private RedisService redisService;

    @Resource
    private FileService fileService;


    @Override
    public boolean deleteByTypeId(Integer typeId) {
        List<String> keys = getHealthTypeContentCacheKeysByTypeId(typeId);
        if (keys != null && keys.size() > 0) {
            redisService.bathDelHashKey(HEATH_CONTENT_KEY_PREFIX, keys);
        }
        healthTypeContentMapper.deleteByTypeId(typeId);
        return true;
    }

    @Override
    public Page queryPageByTypeId(Page<HealthTypeContent> page, Integer typeId) {
        Page healthTypeContentPage = new LambdaQueryChainWrapper<>(healthTypeContentMapper)
                .eq(HealthTypeContent::getTypeId, typeId)
                .page(page);
        if (healthTypeContentPage.getRecords() != null && healthTypeContentPage.getRecords().size() > 0) {
            ArrayList<HealthTypeContentVo> datas = new ArrayList<>();
            healthTypeContentPage.getRecords().stream().forEach(
                    e -> {
                        HealthTypeContent e1 = (HealthTypeContent) e;
                        HealthTypeContentVo healthTypeContentVo = new HealthTypeContentVo();
                        BeanUtils.copyProperties(e1, healthTypeContentVo);
                        if (StringUtils.isNotBlank(e1.getPath())) {
                            healthTypeContentVo.setAbsolutelyPath(fileHttp.concat(healthContentPath).concat(e1.getPath()));
                        }
                        datas.add(healthTypeContentVo);
                    });
            healthTypeContentPage.setRecords(datas);
        }
        return healthTypeContentPage;
    }

    @Override
    public List<HealthTypeContent> getHealthTypeContentByTypeId(Integer typeId) {
        return new LambdaQueryChainWrapper<>(healthTypeContentMapper)
                .eq(HealthTypeContent::getTypeId, typeId)
                .list();
    }

    @Override
    public List<String> getHealthTypeContentCacheKeysByTypeId(Integer typeId) {
        List<Integer> ids = getHealthTypeContentByTypeId(typeId)
                .stream().map(HealthTypeContent::getId)
                .collect(Collectors.toList());
        List<String> keys = new ArrayList<>();
        if (ids != null && ids.size() > 0) {
            for (Integer id : ids) {
                keys.add(id.toString());
            }
        }
        return keys;
    }

    @Override
    public boolean insert(HealthTypeContent healthTypeContent) throws Exception {
        int rest = healthTypeContentMapper.insert(healthTypeContent);
        if (rest > 0) {
            if (StringUtils.isNotBlank(healthTypeContent.getPath())) {
                List<ExcelImporthealthTypeLanguage> list = fileService.readExcel(filePath.concat(healthContentPath).concat(healthTypeContent.getPath()));
                if (list != null && list.size() > 0) {
                    List<ExcelImporthealthTypeLanguage> data = list.stream().filter(e -> StringUtils.isNotBlank(e.getTranslation())).collect(Collectors.toList());
                    if (data!=null&&data.size()>0){
                        redisService.saveCache(HEATH_CONTENT_KEY_PREFIX, healthTypeContent.getId().toString(), JSONObject.toJSONString(data));
                    }
                }
            }
        }
        return rest > 0 ? true : false;
    }

    @Override
    public String getCacheKey(Integer healthTypeId, Integer healthTypeContentId) {
        return HEATH_CONTENT_KEY_PREFIX
                .concat(healthTypeId.toString().
                        concat(SeparatorConstant.EN_DASH).concat(healthTypeContentId.toString()));
    }

    @Override
    public boolean updateHealthTypeContentById(HealthTypeContent healthTypeContent) {
        if (StringUtils.isNotBlank(healthTypeContent.getPath())) {
            List<ExcelImporthealthTypeLanguage> list = null;
            try {
                list = fileService.readExcel(filePath.concat(healthContentPath).concat(healthTypeContent.getPath()));
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            if (list != null && list.size() > 0) {
                List<ExcelImporthealthTypeLanguage> data = list.stream().filter(e -> StringUtils.isNotBlank(e.getTranslation())).collect(Collectors.toList());
                if (data!=null&&data.size()>0){
                    redisService.saveCache(HEATH_CONTENT_KEY_PREFIX, healthTypeContent.getId().toString(), JSONObject.toJSONString(data));
                }
            }
        }else {
            redisService.deleteCache(HEATH_CONTENT_KEY_PREFIX,healthTypeContent.getId().toString());
        }
        return updateById(healthTypeContent);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Integer id) {
        HealthTypeContent healthTypeContent = getHealthTypeContentById(id);
        if (healthTypeContent != null) {
            redisService.deleteCache(HEATH_CONTENT_KEY_PREFIX, id.toString());
            healthTypeContentMapper.deleteById(id);
        }
        return true;
    }

    @Override
    public HealthTypeContent getHealthTypeContentById(Integer id) {
        return new LambdaQueryChainWrapper<>(healthTypeContentMapper)
                .eq(HealthTypeContent::getId, id)
                .one();
    }

}
